package com.api.sw.duban.web;

import com.weaver.formmodel.util.FileHelper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Hashtable;

/**
 * Title:        ecology
 * Description:  for ecology system
 * Copyright:    Copyright (c) 2001
 * Company:      weaver
 *
 * @author liuyu
 * @version 1.0
 */

public class WordOut extends HttpServlet {

    private Hashtable styleht = null ;
	private String agent = "";

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	String namePath = Util.null2String(req.getParameter("path"));
    	HttpSession session = req.getSession();
    	User user = (User) req.getSession(true).getAttribute("weaver_user@bean");
    	if(user == null){
    		new BaseBean().writeLog("请先登录，才能下载此文件："+namePath);
    		return;
    	}
        String action = Util.null2String(req.getParameter("action"));

        if("expInfoWord".equals(action)){   //word导出
            wordOut(req,res);
            return;
        }
    }


    private String handleSlash(String str){
	    return str.replaceAll("/","");
	}

    public void wordOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filename =   "AAA.doc";
        XWPFDocument document = new XWPFDocument();
        String agent = request.getHeader("user-agent");
        if(agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari")){
            if(agent.contains("Safari")){
                filename = URLDecoder.decode(filename, "UTF-8");
            }
            filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
        }
        filename = handleSlash(filename);
        filename = filename.replace("%2F","");
        filename = filename.replaceAll("\\+", "%20");//空格编码的时候会变成+号
        response.setHeader("content-disposition","attachment; filename=\""+filename +"\"");

        ServletOutputStream out=response.getOutputStream();
        String contentType = FileHelper.getMimeType(filename);
        response.setContentType(contentType);

        document.write(out);
        out.flush();
        out.close();
        document.close();
    }
}